import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layouts/Layout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'dashboard' }
      },
      {
        path: 'students',
        name: 'Students',
        component: () => import('@/views/student/StudentList.vue'),
        meta: { title: '学生管理', icon: 'user' }
      },
      {
        path: 'students/add',
        name: 'StudentAdd',
        component: () => import('@/views/student/StudentForm.vue'),
        meta: { title: '添加学生', hidden: true }
      },
      {
        path: 'students/edit/:id',
        name: 'StudentEdit',
        component: () => import('@/views/student/StudentForm.vue'),
        meta: { title: '编辑学生', hidden: true }
      },
      {
        path: 'teachers',
        name: 'Teachers',
        component: () => import('@/views/teacher/TeacherList.vue'),
        meta: { title: '教师管理', icon: 'team' }
      },
      {
        path: 'classes',
        name: 'Classes',
        component: () => import('@/views/class/ClassList.vue'),
        meta: { title: '班级管理', icon: 'apartment' }
      },
      {
        path: 'courses',
        name: 'Courses',
        component: () => import('@/views/course/CourseList.vue'),
        meta: { title: '课程管理', icon: 'book' }
      },
      {
        path: 'grades',
        name: 'Grades',
        component: () => import('@/views/grade/GradeList.vue'),
        meta: { title: '成绩管理', icon: 'bar-chart' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 动态导入store，避免循环依赖
  import('@/store').then(({ useUserStore }) => {
    const userStore = useUserStore()
    const accessToken = localStorage.getItem('accessToken')
    
    // 如果有token但store中没有用户信息，则初始化用户信息
    if (accessToken && !userStore.userInfo) {
      userStore.initUserInfo()
    }
    
    if (to.meta.requiresAuth && !accessToken) {
      next('/login')
    } else if (to.path === '/login' && accessToken) {
      next('/dashboard')
    } else {
      next()
    }
  })
})

export default router